package com.test.javafaq_portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.javafaq_portal.entity.Answer;
import com.test.javafaq_portal.entity.Question;
import com.test.javafaq_portal.entity.User;
import com.test.javafaq_portal.mapper.AnswerMapper;
import com.test.javafaq_portal.mapper.QuestionMapper;
import com.test.javafaq_portal.mapper.UserMapper;
import com.test.javafaq_portal.service.IAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.javafaq_portal.service.IUserService;
import com.test.javafaq_portal.service.ServiceException;
import com.test.javafaq_portal.vo.AnswerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    IUserService userService;
    @Autowired
    UserMapper userMapper;

    @Autowired
    AnswerMapper answerMapper;
    @Override
    public List<Answer> getAnswersByQuestionId(Integer questionId) {
        if (questionId == null)
            throw ServiceException.notFound("id不能为空!");
        QueryWrapper<Answer> query = new QueryWrapper<>();
        query.eq("quest_id",questionId);
        //List<Answer> answers = answerMapper.selectList(query);
        List<Answer> answers = answerMapper.findAnswersWithCommentByQuestionId(questionId);
        return answers;
    }
    //添加回答问题
    @Override
    @Transactional
    public Answer answerQuestion(AnswerVo answerVo) {
        //获取用户信息
        String username = userService.currentUsername();
        User u = userMapper.findUserByUsername(username);

        Integer questionId = answerVo.getQuestionId();
        Question question = questionMapper.selectById(questionId);
        LocalDateTime time = LocalDateTime.now();
        Answer answer = new Answer()
                .setContent(answerVo.getContent())
                .setUserId(question.getUserId())
                .setLikeCount(0)
                .setCreatetime(time)
                .setUserNickName(u.getNickname())
                .setQuestId(answerVo.getQuestionId())
                .setAcceptStatus(1);
        boolean save = save(answer);
        if(!save){
            throw ServiceException.busy();
        }
        return answer;
    }
}
